import random
import matplotlib.pyplot as plt
import numpy as np

class Node:
    def __init__(self, id, p):
        self.id = id
        self.p = p

    def send(self):
        return random.random() < self.p

class SlottedALOHA:
    def __init__(self, num_nodes, slot_time):
        self.nodes = [Node(i, 0.34) for i in range(num_nodes)]
        self.slot_time = slot_time

    def simulate(self, num_slots):
        throughputs = []  # 存储吞吐量
        for slot in range(1, num_slots + 1):
            successful_transmissions_count = 0
            for node in self.nodes:
                if node.send():
                    successful_transmissions_count += 1
            throughput = successful_transmissions_count / len(self.nodes)
            throughputs.append(throughput)

        # 使用移动平均平滑吞吐量数据
        smoothed_throughputs = self.smooth_data(throughputs, window_size=2000)

        return smoothed_throughputs

    def smooth_data(self, data, window_size):
        smoothed_data = []
        for i in range(len(data)):
            start_index = max(0, i - window_size + 1)
            end_index = i + 1
            window_data = data[start_index:end_index]
            smoothed_value = np.mean(window_data)
            smoothed_data.append(smoothed_value)
        return smoothed_data

if __name__ == '__main__':
    num_nodes = 3  # 节点数量
    slot_time = 1  # 时隙长度
    num_slots = 10000  # 模拟的时隙数量

    aloha = SlottedALOHA(num_nodes, slot_time)
    throughputs = aloha.simulate(num_slots)
    np.savetxt('rewards/only_SA_111.txt', throughputs)
    # 绘制平滑后的吞吐量随时间变化的折线图
    plt.plot(range(1, num_slots + 1), throughputs,lw=1)
    plt.xlabel('Time Slots')
    plt.ylabel('Throughput')
    plt.title('Smoothed Throughput over Time in Slotted ALOHA')
    plt.ylim(0, 1)  # 设置纵轴范围为0到1
    plt.show()
